// 登录
import React,{useState} from 'react';
import {View, Text, StyleSheet, StatusBar,Image,TextInput} from 'react-native';
import {windowWidth, windowHeight, getHeight, getWidth} from '@/utils/index';
import IconFont, {IconNames} from '../../assets/iconfont';
import Touchable from '../../components/Touchable';
// 连接到dva,react-redux本身充当一个桥梁的作用
import {connect, ConnectedProps} from 'react-redux';
import {RootState} from "@/models/index";
import Toast from 'react-native-root-toast';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { IUserInfo } from '@/models/user';
const mapStateToProps = ({users, loading}: RootState) => {
  return {
    // 在触发getUserInfo方法时加上加载效果
    loading: loading.effects['users/login'],
  };
};
const connector = connect(mapStateToProps);
type ModelState = ConnectedProps<typeof connector>;
interface IProps extends ModelState{
  navigation: {goBack: any, navigate:any};
}
interface IFormData {
  username:string;
  password:string;
}
const Login = (props: IProps) => {
  const {dispatch, navigation} = props;
  const [formData,setFormData] = useState<IFormData>({
    username:"",
    password:""
  })
  const handleRegister = () =>{
    navigation.navigate("Register");
  }
  // 收集登录的username和password
  const onChangeText = (text: string, name: string) => {
    console.log('name1111111111111', name, 'text111111111111111111', text);
    let obj = {[name]: text};
    let newFormData = Object.assign(formData, obj);
    setFormData(newFormData);
  };
  const handleLogin = () => {
    // 请求登录接口
    dispatch({
      type: 'users/login',
      payload: {
        formData: formData,
        // async
        callback: (data:{
          token:string;
          loginUserInfo: IUserInfo
        }) => {
          console.log("loginCallBack",data.loginUserInfo._id)
          // 登录成功之后请求触发当前用户的接口
          dispatch({
            type: 'users/getCurrentUser',
            payload: {
              user_id: data.loginUserInfo._id,
              callback: (data:IUserInfo[]) => {   
                console.log("登录成功之后执行了当前用户的回调",data[0])
                data[0] && AsyncStorage.setItem('currentUserInfo', JSON.stringify(data[0]));
              },
            },
          });
          // 200才会调用callback
          Toast.show('登录成功', {
            position: Toast.positions.CENTER,
            duration: Toast.durations.LONG,
            shadow: true,
            animation: true,
          });
    
          // 如果注册的code为200，跳转回刚才想访问的页面
          navigation.goBack();
        },
      },
    })
  }
  return (
    <View style={styles.loginBox}>
      <StatusBar backgroundColor="#fff" barStyle="dark-content" />
      <Touchable
        onPress={() => {
          navigation.goBack();
        }}>
        <IconFont name="icon-fanhui" size={26} color={'#999'}></IconFont>
      </Touchable>
      <View style={styles.mainBox}>
        <Text style={styles.bigTitle}>XiPai</Text>
        {/* source={require('@expo/snack-static/react-native-logo.png')} */}
        {/* <Image source={require("../../assets/localImage/login_image.png")} style={styles.image}/> */}
        {/* <Image source={require("../../assets/localImage/login_title.png")} style={styles.image1}/>
        <Image source={require("../../assets/localImage/login_tab.png")} style={styles.image2}/> */}
        <Text style={styles.title}>一个摄影爱好者的平台</Text>
        <Text style={styles.title}>A platform for photography lovers</Text>
        <TextInput placeholder='请输入用户名' style={[styles.inputBox, styles.inputBoxTop]}
         onChangeText={text => onChangeText(text,"username")}></TextInput>
        <TextInput placeholder='请输入密码' style={styles.inputBox} secureTextEntry={true}
         onChangeText={text => onChangeText(text,"password")}></TextInput>
        <Touchable onPress={handleLogin}><Text style={styles.loginBtn}>登录</Text></Touchable>
        <Touchable onPress={handleRegister}><Text style={styles.toRegister}>还么有账号？点击注册</Text></Touchable>
      </View>
    </View>
  );
};
const styles = StyleSheet.create({
  loginBox: {
    padding: 10,
    backgroundColor: '#fff',
    width: windowWidth,
    height: windowHeight,
  },
  mainBox: {
    marginTop:70,
    display:"flex",
    alignItems:"center",
    
  },
  bigTitle: {
    fontSize:70,
    fontWeight:"700",
    color:"#A75E5E",
  },
  title: {
    fontSize:12,
    fontWeight:"700",
    fontFamily:"Edwardian Script ITC",
    color:"#A75E5E",
  },
  image: {
    width:200,
    height:130,
    resizeMode: 'stretch',
    marginBottom:10,
  },
  image1: {
    width:150,
    height:16,
    resizeMode: 'stretch',
  },
  image2:{
    width:240,
    height:18,
    resizeMode: 'stretch',
  },
  inputBox: {
    width:getWidth(80),
    height:40,
    borderBottomColor:"#A75E5E",
    borderBottomWidth:1,
  },
  inputBoxTop: {
    marginTop:20
  },
  loginBtn:{
    width:getWidth(50),
    height:35,
    color:"#fff",
    textAlign:"center",
    backgroundColor:"#A75E5E",
    marginVertical:35,
    borderRadius:35,
    lineHeight:35
  },
  toRegister:{
    color: "#A75E5E",
    fontSize:14
  }
});
export default connector(Login);
